// 父子进程进程间通信

// 学习知识储备
// pipe接口         int pipe(int pipfd[2])  pipfd[0]:读端   pipfd[1]:写端
// snprintf接口     int snprintf(char* str, size_t size, const char* format, ...)
// write接口        ssize_t write(int fd, const void* buf, size_t count)
// read接口         ssize_t read(int fd, void* buf, size_t count)

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

#define N 2
#define NUM 1024

// 子进程写端
void Write(int wfd)
{
    // 写入给父进程的三种数据
    string s = "hello, I am child";
    pid_t self = getpid();      
    int number = 0;
    
    char buffer[NUM];
    while(true)
    {
        // 构建发送字符串
        buffer[0] = 0;
        snprintf(buffer, sizeof(buffer), "%s - %d - %d", s.c_str(), self, number++);

        // 测试snprintf功能
        // cout << "buffer: " << buffer << endl;
        // 测试结果：buffer: hello, I am child - 31094 - 0

        // 发送写入给父进程，system call
        write(wfd, buffer, strlen(buffer));

        sleep(1);

        if(number >= 5) break;

    }
}

// 父进程读端
void Reader(int rfd)
{
    char buffer[NUM];
    int cnt = 0;
    while(true)
    {
        buffer[0] = 0;
        // 系统调用system call，调用子进程写的数据
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "father get a message[> " << getpid() << " <]" << buffer << endl;
        }
        else if(n == 0)
        {
            cout << "father read file done!" << endl;
            break;
        }
        else break;

        sleep(1);
        cnt++;
        if(cnt >= 5) break;
    }
}

int main()
{
    // 首先为父进程创建一个管道
    int pipfd[N] = {0};
    int n = pipe(pipfd);    // 创建一个管道
    if(n < 0)   return 1;

    // 测试pipfd[0]读端和pipfd[1]写端
    // cout << "pipfd[0]: " << pipfd[0] << " , pipfd[1]: " << pipfd[1] << endl;
    // 测试结果：pipfd[0]: 3 , pipfd[1]: 4
    
    // 让child->w, parent->r
    pid_t id = fork();  // 创建子进程
    if(id < 0)  return 2;
    else if(id == 0)
    {
        // child
        close(pipfd[0]);    // child要写，所以关闭读端

        // ipc code
        Write(pipfd[1]);        // 往该文件描述符内写数据

        // 关闭管道
        close(pipfd[1]);
        exit(0);
    }
    // parent
    close(pipfd[1]);

    // ipc code
    Reader(pipfd[0]);   // 读取数据

    // 关闭管道，善后工作
    close(pipfd[0]);
    cout << "father close read fd: " << pipfd[0] << endl;
    sleep(5);

    // 回收子进程，不让其成为僵尸进程
    int status = 0;
    pid_t rid = waitpid(id, & status, 0);
    if(rid < 0) return 3;

    cout << "wait child success: " << rid << ", exit code: " << ((status>>8)&0xFF) << ", exit signal: " << (status&0x7F) << endl;

    sleep(5);
    cout << "father quit!" << endl;

    return 0;
}